package com.ncs.cns.activity.task;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ncs.cns.R;
import com.ncs.cns.business.db.DBHelper;
import com.ncs.cns.business.http.HttpHelper;
import com.ncs.cns.business.service.CommonService;
import com.ncs.cns.business.service.EventService;
import com.ncs.cns.business.service.ResourceService;
import com.ncs.cns.business.service.UserService;
import com.ncs.cns.business.service.UserSessionService;
import com.ncs.cns.business.to.Event;
import com.ncs.cns.business.to.TransferObject;
import com.ncs.cns.business.util.JsonConvertor;
import com.ncs.cns.business.util.UploadUtil;

public class UploadImgTask extends AsyncTask<String, Integer, String> {
	
	protected HttpHelper helper;
	protected CommonService commService;
	protected UserSessionService sessionService;
	protected UserService userService;
	protected ResourceService resourceService;
	protected EventService eventService;
	protected DBHelper dbHelper;
	private List<String> photoList = null;
	private Context c;
	private Activity a;
	private int eventId;
	public UploadImgTask(List<String> photoList,Activity a) {
		this.a = a;
		c = a.getApplicationContext();
		commService = new CommonService(c);
		sessionService = new UserSessionService(c);
		userService =new UserService(c);
		resourceService = new ResourceService(c);
		eventService = new EventService(c);
		helper = new HttpHelper(a);
		dbHelper = new DBHelper(c);
		this.photoList = photoList;
	}
	
	
	@Override
	protected String doInBackground(String... params) {
		String result = "";
		if(photoList.size() != 0){             		
			UploadUtil upload = new UploadUtil(helper.getHttpClient(20,240));
			result = upload.uploadFile(params[0], params[1],this.photoList);
			JsonConvertor json = JsonConvertor.getInstance();
			TransferObject obj = (TransferObject) json.convert2Object(params[1], TransferObject.class);
			Event event = obj.getCurrentEvent();
			eventId = event.getEventId();
		}
		return result;
	}
	
	@Override
	protected void onPostExecute(String result) {		
		if(result != null && !result.equals("")){	
			Toast.makeText(c, "上传图片成功", Toast.LENGTH_SHORT).show();
			eventService.updateEventStatusById(eventId, "A");				
		}else{
			Toast.makeText(c, "上传图片失败,请检查你的网络或重试", Toast.LENGTH_SHORT).show();	
			eventService.updateEventStatusById(eventId, "F");
		}	
		RadioGroup radio = (RadioGroup)a.findViewById(R.id.main_tab_group);
		if(radio.getChildAt(1).getTag() != null && (Boolean)radio.getChildAt(1).getTag()){
			radio.getChildAt(3).performClick(); 
			radio.getChildAt(1).performClick(); 				
		}
	}
}
